/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-common
*
* @File name : DloadImgUtil.java
*
* @Author : Administrator
*
* @Date : 2017年8月17日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年8月17日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package org.marketing.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import net.sf.json.JSONObject;


/**
 * @author Administrator
 * @date 2017年8月17日
 */

public class DloadImgUtil {

    private static Logger logger = Logger.getLogger(DloadImgUtil.class);
    
//    public static String genAccessToken() {
//        logger.info("----------------gen wechatAccessToken");
////        测试环境
////        String appid = "wxba1a78acbd889dbc";
////        String secret = "a36c797e180fd1c046422391b3bcdc99";
////      生产环境
//        String appid = "wxc51f9980b85cdb56";
//        String secret = "cdcd1f93a66535d1a553f62678d81a52";
//        String reqUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//        if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(secret))
//            return "";
//        reqUrl = reqUrl.replace("APPID", appid).replace("APPSECRET", secret);
//        System.out.println(reqUrl);
//        
//        String sendGetRequest = HttpClientUtil.sendGetRequest(reqUrl);
//        JSONObject fromObject = JSONObject.fromObject(sendGetRequest);
//        AccessToken.setAccessToken(fromObject.get("access_token")
//                .toString());
//        AccessToken.setExpiresIn(fromObject.get("expires_in")
//                .toString());
//        return AccessToken.getAccessToken();
//        
//    }
    /**
     * 根据内容类型判断文件扩展名
     *
     * @param contentType 内容类型
     * @return
     */
    public static String getFileexpandedName(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType)) fileEndWitsh = ".jpg";
        else if ("audio/mpeg".equals(contentType)) fileEndWitsh = ".mp3";
        else if ("audio/amr".equals(contentType)) fileEndWitsh = ".amr";
        else if ("video/mp4".equals(contentType)) fileEndWitsh = ".mp4";
        else if ("video/mpeg4".equals(contentType)) fileEndWitsh = ".mp4";
        return fileEndWitsh;
    }

    /**
     * 获取媒体文件
     * 
     * @param accessToken 接口访问凭证
     * @param mediaId 媒体文件id
     * @param savePath 文件在本地服务器上的存储路径
     */
    public static List<String> downloadMedia(List<String> list,String token) {
        String accessToken = token;
//      测试环境
//        String savePath = "/home/lyh_test/file_remote/forum";
//        String uri = "http://wxtest.gmmc.com.cn/wx/fs01/forum/";
//      生产环境
        String savePath = "/home/appadmin/appfile/fs01/forum";
        String uri = "http://carowner.yonyouauto.com/fs01/forum/";
        logger.info("传入的toen为："+accessToken);
        List<String> result = new ArrayList<String>();
        String filePath = null;
        String fileExt = null;
        for(int a = 0 ;a<list.size();a++){
            String mediaId = list.get(a);
            File file = null;
            // 拼接请求地址
            String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
            requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
            try {
                URL url = new URL(requestUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setRequestMethod("GET");

                if (!savePath.endsWith("/")) {
                    savePath += "/";
                }
                // 根据内容类型获取扩展名
                fileExt = DloadImgUtil.getFileexpandedName("image/jpeg");
                // 将mediaId作为文件名
                filePath = savePath + mediaId + fileExt;
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                file = new File(filePath);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[8096];
                int size = 0;
                //代码扫描 8 10.18
                try{
                	while ((size = bis.read(buf)) != -1)
                        fos.write(buf, 0, size);
                }catch (Exception e) {
                	filePath = null;
                    String error = String.format("下载媒体文件失败：%s", e);
                    logger.info(error);
                }finally{
                	fos.close();
                    bis.close();
                    conn.disconnect();
                }
                String info = String.format("下载媒体文件成功，filePath=" + filePath);
                logger.info(info);
            } catch (Exception e) {
                filePath = null;
                String error = String.format("下载媒体文件失败：%s", e);
                logger.info(error);
            }
            result.add(uri+mediaId+fileExt);
        }
        return result;
    }
}
